package hot100;

import comment.ListNode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author: wzp
 * @CreateTime: 2024-09-17  11:39
 * @Description:
 * @Version: 1.0
 */
public class hot_160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null||headB==null){
            return null;
        }
        int headALength=0;
        ListNode headATemp=headA;
        while (headATemp!=null){
            headALength++;
            headATemp=headATemp.next;
        }
        int headBLength=0;
        ListNode headBTemp=headB;
        while (headBTemp!=null){
            headBLength++;
            headBTemp=headBTemp.next;
        }
        int num=Math.abs(headALength-headBLength);
        if(headALength>headBLength){
            while (num>0){
                headA=headA.next;
                num--;
            }
        }else {
            while (num>0){
                headB=headB.next;
                num--;
            }
        }
        while (headA!=headB){
            headA=headA.next;
            headB=headB.next;
        }
        return headA;
    }





    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {

        if(headA==null||headB==null){
            return null;
        }
        HashSet<ListNode> set=new HashSet<>();
        while (headA!=null){
            set.add(headA);
            headA=headA.next;
        }
        ListNode result=null;
        while (headB!=null){
            if(set.contains(headB)){
                result=headB;
                break;
            }
            headB=headB.next;
        }
        return result;

    }



    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        List<ListNode> listA = new ArrayList<>();
        List<ListNode> listB = new ArrayList<>();
        ListNode result= null;
        while (headA != null){
            listA.add(headA);
            headA = headA.next;
        }
        while (headB != null){
            listB.add(headB);
            headB = headB.next;
        }
        for (int i = 0; i < listA.size(); i++) {
            for (int j = 0; j < listB.size(); j++){
                if(listA.get(i) == listB.get(j)){
                    result = listA.get(i);
                    break;
                }
            }
        }
        return result;
    }
}
